<template>
  <el-card>
    <el-button
      type="primary"
      icon="el-icon-plus"
      size="min"
      style="margin-top: 20px"
      @click="showDialog"
    >
      添加品牌
    </el-button>
    <el-table :data="trademarkList" border style="width: 100%; margin: 20px 0">
      <el-table-column label="序号" type="index" width="80" align="center">
      </el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template slot-scope="{ row }">
          <img
            :src="row.logoUrl"
            :alt="row.tmName"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            icon="el-icon-edit"
            size="min"
            style="color: orange"
            @click="showDialog(row)"
          >
            更新品牌
          </el-button>
          <el-button
            icon="el-icon-delete"
            size="min"
            style="color: red"
            @click="removeTrademark(row)"
          >
            删除品牌
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="limit"
      layout="->,prev, pager, next, jumper, -> , sizes, total"
      :total="total"
    >
    </el-pagination>

    <!-- 添加 -->
    <el-dialog
      title="添加品牌"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="ruleForm" :rules="rules" ref="addForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="ruleForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="110px">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.logoUrl"
              :src="ruleForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTrademark"> 确 定 </el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getTrademarkListApi,
  addTrademarkListApi,
  upDateTrademarkApi,
  removeTrademarkApi,
} from "@/api/product/trademark/trademark";
export default {
  name: "Trademark",
  data() {
    return {
      page: 1,
      limit: 3,
      total: 15,
      //品牌列表
      trademarkList: [],
      //切换
      dialogVisible: false,
      ruleForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "change",
          },
        ],
        logoUrl: [
          { required: true, message: "请上传品牌LOGO", trigger: "change" },
        ],
      },
    };
  },
  async mounted() {
    this.getTrademarkList();
  },
  methods: {
    //获取某页品牌列表
    async getTrademarkList(page) {
      const res = await getTrademarkListApi(
        page ? page : this.page,
        this.limit
      );
      const { records, total } = res.data;
      this.trademarkList = records;
      this.total = total;
      if (page) {
        this.page = page;
      }
    },
    //点击添加、更新
    showDialog(row) {
      // console.log(row)
      if (row.id) {
        this.ruleForm = { ...row };
      }
      this.dialogVisible = true;
    },
    //点击确定添加
    addTrademark() {
      console.log(this.$refs.addForm);
      this.$refs.addForm.validate(async (valid) => {
        // console.log(valid)
        if (valid) {
          try {
            console.log(this.ruleForm);
            if (this.ruleForm.id) {
              //发送更新请求
              await upDateTrademarkApi(this.ruleForm);
            } else {
              //发送添加请求
              await addTrademarkListApi(this.ruleForm);
            }
            //弹窗提示成功
            this.$message({
              message: `${this.ruleForm.id ? "更新" : "添加"}品牌成功`,
              type: "success",
            });
            //更新页面
            this.getTrademarkList();

            this.ruleForm = {
              tmName: "",
              logoUrl: "",
            };
            //隐藏弹窗
            this.dialogVisible = false;
          } catch (error) {
            this.$message({
              message: "添加失败!!!" + error,
            });
          }
        } else {
          console.log("保存失败");
          return false;
        }
      });
    },
    //删除品牌
    async removeTrademark(val) {
      const { id } = val;
      await removeTrademarkApi(id);
      //更新页面
      this.getTrademarkList();
      //弹窗提示成功
      this.$message({
        message: `删除品牌成功`,
        type: "success",
      });
    },
    //更改每页条数触发
    handleSizeChange(val) {
      this.limit = val;
      this.getTrademarkList();
    },
    //更改页数触发
    handleCurrentChange(val) {
      this.getTrademarkList(val);
    },
    //蒙版关闭事件
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 成功时的钩子
    handleAvatarSuccess(res, file) {
      this.ruleForm.logoUrl = res.data;
    },
    //上传文件之前触发，参数为上传的文件,false为停止上传
    beforeAvatarUpload(file) {
      const types = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-icon-plus {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
